import { Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    ComboboxItemDto,
    Base_UserCardServiceProxy,
    Base_UserCardDto
} from '@shared/service-proxies/stock-service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditUserCardModal',
    templateUrl: './create-or-edit-user-card-modal.component.html'
})
export class CreateOrEditUserCardModalComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    depts: ComboboxItemDto[];

    card: Base_UserCardDto;

    filter = '';

    constructor(injector: Injector, private _userCardService: Base_UserCardServiceProxy) {
        super(injector);
    }

    show(cardId?: string): void {
        const self = this;
        self.active = true;

        this._userCardService.getUserCardForEdit(cardId).subscribe(result => {
            this.card = result.userCard;
            this.depts = result.departments;
            self.modal.show();
        });
    }

    onShown(): void {
        document.getElementById('cardNumber').focus();
    }

    save(): void {
        const self = this;
        this.saving = true;
        this._userCardService
            .createOrUpdateUserCard(this.card)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
